//
//  MyTextView.m
//  sandbox
//
//  Created by 杨岑 on 27/11/2016.
//  Copyright © 2016 杨岑. All rights reserved.
//

#import "MyTextView.h"
#import "Test.h"


@implementation MyTextView

- (void)undoReplacingAttributedString:(NSAttributedString*)oldString with:(NSAttributedString*)newString range:(NSRange)range
{
    if ([self shouldChangeTextInRange:range replacementString:newString.string])
    {
        if (!oldString) oldString = [self.textStorage attributedSubstringFromRange:range];
        NSRange newRange = {range.location, newString.length};
        [[self.undoManager prepareWithInvocationTarget:self] undoReplacingAttributedString:newString with:oldString range:newRange];
        //[self.undoManager setActionName:@"Parsed"];
        [self.textStorage replaceCharactersInRange:range withAttributedString:newString];
        [self didChangeText];
    }
}

- (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard type:(NSString *)type
{
    _pasted = YES;
    NSLog(@"%s: %@", __PRETTY_FUNCTION__, type);
    _pastedText = [[NSPasteboard generalPasteboard] stringForType:NSPasteboardTypeString];
    NSLog(@"Text to be pasted: %@", self.pastedText);

#ifdef PASTE_METHOD_DIRECT
    NSRange range = [self rangeForUserTextChange];
    NSMutableAttributedString* newString = [[NSMutableAttributedString alloc] initWithString:_pastedText attributes:@{NSForegroundColorAttributeName: [NSColor redColor]}];
    [newString removeAttribute:NSFontAttributeName range:NSMakeRange(0, newString.length)];
    [self undoReplacingAttributedString:nil with:newString range:range];
    return YES;
#else
    return [super readSelectionFromPasteboard:pboard type:type];
#endif
}

- (BOOL)readSelectionFromPasteboard:(NSPasteboard *)pboard
{
    return [super readSelectionFromPasteboard:pboard];
}

@end
